#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@Time :    2019/8/31 19:56
@Author:  ThinHeader
@File: qinius.py
@Software: PyCharm
"""

# -*- coding: utf-8 -*-
from qiniu import Auth, PersistentFop, build_op, op_save, urlsafe_base64_encode, urlsafe_base64_decode
import requests


class QNInfo(object):
    """七牛配置类"""
    QINIU_ACCESS_KEY = 'mcWDw9QdBnZS3utP2ZPYUF2Rr4bQ6_10O4rvg-Et'
    QINIU_SECRET_KEY = 'vsn_EDRt4pB4Fzo-aXMxYEHTvqHcgPOJ96iw3hpk'

    QINIU_BUCKET_HTTPS = {'qixiaobao': 'static.dongpouu.com',  # 示例
    }
    QINIU_BUCKET_HTTP = {'qixiaobao': 'static.dongpouu.com',  # 示例
    }
    PIPELINE = ['default', 'low', 'normal', 'high']
    HIGHT_WIDTH = '1024x576'

    # HLS = True
    HLS = False


class QNApi(object):
    """七牛管理类"""

    def __init__(self):
        self.q = Auth(QNInfo.QINIU_ACCESS_KEY, QNInfo.QINIU_SECRET_KEY)

    def getuptoken(self, bucket, filename=None, params=None):
        """获得上传凭证"""
        if bucket not in QNInfo.QINIU_BUCKET_HTTPS:
            return ''
        # q = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
        # if params is None:
        #     token = q.upload_token(QINIU_BUCKET_HTTP[bucket_type],
        #                            filename,
        #                            policy={'returnBody': "{'key': $(key), 'hash': $(etag), 'size': $(fsize)}"})
        # else:
        #     token = q.upload_token(QINIU_BUCKET_HTTP[bucket_type], filename, policy=params)
        token = self.q.upload_token(bucket, key=filename, policy=params)
        return token

    def getdwurl(self, domain, key, security=False):
        """获得下载链接"""
        if domain not in QNInfo.QINIU_BUCKET_HTTPS:
            return ''

        if security:
            base_url = 'https://%s/%s' % (QNInfo.QINIU_BUCKET_HTTPS[domain], key)
        else:
            base_url = 'http://%s/%s' % (QNInfo.QINIU_BUCKET_HTTP[domain], key)
        private_url = self.q.private_download_url(base_url, expires=3600)
        return private_url

    def getavinfourl(self, domain, key):
        """获得音视频元信息"""
        if domain not in QNInfo.QINIU_BUCKET_HTTPS.values():
            return ''

        base_url = 'http://%s/%s?avinfo' % (domain, key)
        private_url = self.q.private_download_url(base_url, expires=3600)
        return private_url

    def getm3u8url(self, domain, key, security=False):
        """获得下载链接"""
        if domain not in QNInfo.QINIU_BUCKET_HTTPS:
            return ''

        if security:
            base_url = 'https://%s/%s?pm3u8/0/expires/43200' % (QNInfo.QINIU_BUCKET_HTTPS[domain], key)
        else:
            base_url = 'http://%s/%s?pm3u8/0/expires/43200' % (QNInfo.QINIU_BUCKET_HTTP[domain], key)
        private_url = self.q.private_download_url(base_url, expires=43200)
        return private_url

    def getimage(self, bucket, key, imageview=False, private=False):
        """获得图片下载链接"""
        if key:
            if imageview:
                key += '?imageView2/1/w/'
            if private:
                return self.getdwurl(QNInfo.QINIU_BUCKET_HTTPS[bucket], key)
            return 'http://%s/%s' % (QNInfo.QINIU_BUCKET_HTTPS[bucket], key)
        return ''

    def verify_callback(self, request):
        """验证回调"""
        authorization = request.META['Authorization']
        path = request.get_host() + request.path
        body = request.body
        content_type = request.META['CONTENT_TYPE']
        return self.q.verify_callback(authorization, path, body, content_type)

    def pipeline(self, file_size):
        """根据文件大小选择转换队列"""
        if file_size == 0:
            return QNInfo.PIPELINE[0]
        elif file_size <= 50 * 1024 * 1024:
            return QNInfo.PIPELINE[3]
        elif file_size <= 100 * 1024 * 1024:
            return QNInfo.PIPELINE[2]
        elif file_size <= 200 * 1024 * 1024:
            return QNInfo.PIPELINE[1]
        else:
            return QNInfo.PIPELINE[0]

    def hls(self, key, bucket=None, hlsKey=None, hlsKeyUrl=None,
            hlsKeyType=None, notify_url=None, pipeline=None, logo=None):
        """hls转码"""
        if bucket is None:
            bucket = 'video'
        if pipeline is None:
            pipeline = 'normal'

        if logo is None:
            logo = 'http://7xklq1.com2.z0.glb.qiniucdn.com/xuemei_logo.png'

        pfop = PersistentFop(self.q, bucket, pipeline, notify_url)
        # 转码为m3u8格式并加上水印
        opear = 'avthumb/m3u8/segtime/30/vcodec/libx264/s/' + QNInfo.HIGHT_WIDTH + '/wmImage/' + urlsafe_base64_encode(
            logo)
        if hlsKey is not None and hlsKeyUrl is not None:
            opear += '/hlsKey/' + urlsafe_base64_encode(hlsKey) + \
                     '/hlsKeyUrl/' + urlsafe_base64_encode(hlsKeyUrl)
        if hlsKeyType is not None:
            opear += '/hlsKeyType/' + str(hlsKeyType)

        op = op_save(opear, bucket, key + QNInfo.HIGHT_WIDTH)
        ops = []
        ops.append(op)
        ret, info = pfop.execute(key, ops, 1)
        return ret, info
        # print(info)
        # assert ret['persistentId'] is not None

    def geturl(self, bucket, key, private=False):
        """获得七牛指定bucket中image地址"""
        if key:
            if private:
                return self.getdwurl(QNInfo.QINIU_BUCKET_HTTPS[bucket], key)
            return 'https://%s/%s' % (QNInfo.QINIU_BUCKET_HTTPS[bucket], key)
        return ''

    def getPicUrl(self, key, private=False):
        if key:
            return self.geturl('show', key, private)
        return ''

    def getHttpPicUrl(self, key):
        if key:
            return 'http://%s/%s' % (QNInfo.QINIU_BUCKET_HTTPS['show'], key)
        return ''

    def getAvatar(self, key, private=False):
        if key:
            return self.getAvatarHttpUrl('avatar', key, private)
        return ''

    def getAvatarHttpUrl(self, bucket, key, private=False):
        if key:
            return 'https://%s/%s' % (QNInfo.QINIU_BUCKET_HTTPS[bucket], key)
        return ''

    def putb64(self, data, bucket, key):
        headers = {'Content-Type': 'application/octet-stream',
                   'Authorization': 'UpToken %s' % self.getuptoken(bucket, key)}
        req = requests.post('http://upload.qiniu.com/putb64/-1/key/%s' % urlsafe_base64_encode(key), data=data,
                            headers=headers)
        return req.json()
